<template>
  <div class="home-container">
    <div class="batch-container">
      <div class="container-head">
        <div @click="isCollapseFn" class="breadcrumb-icon">
          <el-icon v-if="isCollapse"><Expand /></el-icon>
          <el-icon v-else><Fold /></el-icon>
        </div>
        <div class="export-section" style="margin-right: 30px;margin-top: -3px;float: right;">
          <el-button class="blue-btn" @click="exportTableData">导出表格数据</el-button>
        </div>
      </div>
      <div class="container-body">
        <div :class="isCollapse ? 'table-content' : 'table-content-full'">
          <div class="test">
            
            <el-table :data="tableData" :style="{width: tableWidth + 'px'}">
              <!-- <el-table-column fixed type="selection" min-width="45" /> -->
              <el-table-column fixed label="论文" min-width="200">
                <template #default="scope">
                  <div>{{scope.row.originalFilename}}</div>
                  <div>
                    <el-button class="name-btn" @click="previewFn(scope.row.filePath)">预览</el-button>
                    <el-button class="name-btn blue-btn" type="primary" @click="readingFn(scope.row)">查看解析</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-for="column in columnOrder"
                :key="column.id"
                :prop="column.id"
                :label="column.name"
                min-width="350">
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="column-content" v-if="isCollapse">
          <div class="column-head">管理列</div>
          <div class="column-body">
            <div class="current-column">
              <div class="column-title">当前列</div>
              <div class="column-title" v-if='columnOrder && columnOrder.length === 0' style="color: oklch(44.2% .017 285.786); font-size: 13px">当前列为空</div>
              <div class="column-list" v-else>
                <div class="column-list-item" v-for="item in columnOrder" :key="item.id" @click="deleteColumn(item)">
                  <div><el-icon><Minus /></el-icon></div>
                  <div>{{item.name}}</div>
                </div>
              </div>
            </div>
            <div :class="heightAuto ? 'order-column column-auto' : 'order-column'">
              <div class="column-title">添加列</div>
              <div v-if='columnOrder && columnOrder.length > 20'>
                <el-tooltip
                  class="box-item"
                  content="提取列已达最大值20列"
                  placement="left"
                  :visible='visible'
                >
                  <div class="column-list" v-if="columns.length">
                    <div class="column-list-item disabled" v-for="item in columns" :key="item.id">
                      <div><el-icon><Plus /></el-icon></div>
                      <div>{{item.displayName.zh}}</div>
                    </div>
                  </div>
                  <div class="column-title" v-else style="color: oklch(44.2% .017 285.786); font-size: 13px">当前列为空</div>
                </el-tooltip>
              </div>
              <div v-else>
                <div class="column-list" v-if="columns.length">
                  <div class="column-list-item" v-for="item in columns" :key="item.id" @click="addColumn(item)">
                    <div><el-icon><Plus /></el-icon></div>
                    <div>{{item.displayName.zh}}</div>
                  </div>
                </div>
                <div class="column-title" v-else style="color: oklch(44.2% .017 285.786); font-size: 13px">当前列为空</div>
              </div>
            </div>
            <div class="column-list-more" v-if="!heightAuto && columns.length > 10" @click="heightAuto = true">显示更多</div>
            <div class="column-list-more" v-else-if="heightAuto && columns.length > 10" @click="heightAuto = false">收起</div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
    
</template>

<script setup>
import { watch, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { columnEdit, columnData } from '@/api/user';
import { ElMessage } from 'element-plus';
import MultipleUpload from '../components/MultipleUpload.vue';

const route = useRoute();
const router = useRouter();

const isCollapse = ref(true)
const isCollapseFn = () => {
  isCollapse.value = !isCollapse.value;
}

const tableData = ref([]);
const columnOrder = ref([]);
const allColumns = ref([]);
const columns = ref([]);

const heightAuto = ref(false);

const taskId = ref('');

const tableWidth = ref(100);

watch(columnOrder, (newOrder) => {
  tableWidth.value = 200 + newOrder.length * 350
});

onMounted(() => {
  taskId.value = route.query.task;
  renderData();
})

const addColumn = (item) => {
console.log(item)
  const index = columns.value.findIndex(column => column.id === item.id);
  console.log(index);
  columnOrder.value.push({
    id: item.id,
    name: item.displayName.zh,
  })
  columns.value.splice(index, 1)
  saveColumn();
}

const deleteColumn = (item) => {
  const index = columnOrder.value.findIndex(column => column.id === item.id);
  columnOrder.value.splice(index, 1);
  renderColumns();
  saveColumn();
}

const saveColumn = async () => {
  await columnEdit({columnOrder: columnOrder.value, taskId: taskId.value})
  renderData();
}

const renderColumns = () => {
  let extractColumns = [];
  // 去除已经选择的column
  if (columnOrder.value && columnOrder.value.length > 0) {
    allColumns.value.forEach(item => {
      const index = columnOrder.value.findIndex(column => column.id === item.id);
      if (index === -1) {
        extractColumns.push(item);
      }
    })
    columns.value = extractColumns;
  } else {
    columns.value = allColumns.value
  }
}

const renderData = async () => {
  let res = await columnData(taskId.value);
  if (res.code == '200') {

    const list = res.data.rows;
    columnOrder.value = res.data.columnOrder;
    allColumns.value = res.data.columns;
    renderColumns();

    tableData.value = [];

    list.forEach(item => {
      let info = JSON.parse(JSON.stringify(item));
      info.cellValues.forEach(cell => {
        const obj = columnOrder.value.findIndex(column => column.id === cell.id);
        // 需要展示的数据
        if (obj > -1) {
          info[cell.id] = cell.value
        }
      })
      tableData.value.push(info);
    })
  }
}

const previewFn = (link) => {
  window.open(link, '_blank');
}

const readingFn = (row) => {
  sessionStorage.setItem(row.id, row.originalFilename);
  const routeData = router.resolve({
    name: 'LiteratureDetail',
    query: { task: row.id }
  })
  window.open(routeData.href, '_blank')
}

// 导出表格数据为Excel格式（使用HTML表格，支持样式设置）
const exportTableData = () => {
  if (!tableData.value || tableData.value.length === 0) {
    ElMessage.warning('暂无数据可导出');
    return;
  }
  
  // 准备列信息
  const columnIds = [];
  let headerCells = [];
  
  // 添加论文名称列
  headerCells.push('<th style="width: 200px; text-align: center; font-weight: bold; background-color: #f0f0f0;">论文名称</th>');
  
  // 添加自定义列标题
  if (columnOrder.value && columnOrder.value.length > 0) {
    columnOrder.value.forEach(column => {
      columnIds.push(column.id);
      // 设置较宽的列宽，支持自动换行
      headerCells.push(`<th style="width: 400px; text-align: center; font-weight: bold; background-color: #f0f0f0;">${escapeHtml(column.name)}</th>`);
    });
  }
  
  // 构建HTML表格内容
  let htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <style>
        table {
          border-collapse: collapse;
          width: 100%;
        }
        th, td {
          border: 1px solid #ddd;
          padding: 8px;
          word-wrap: break-word;
          white-space: normal;
        }
        td {
          height: auto;
          min-height: 20px;
        }
        /* 为内容列设置自动换行 */
        td:nth-child(n+2) {
          width: 400px;
        }
      </style>
    </head>
    <body>
      <table>
        <thead>
          <tr>${headerCells.join('')}</tr>
        </thead>
        <tbody>
  `;
  
  // 添加数据行
  tableData.value.forEach(row => {
    let dataCells = [];
    // 添加论文名称
    dataCells.push(`<td style="width: 200px;">${escapeHtml(row.originalFilename)}</td>`);
    
    // 添加各列数据
    columnIds.forEach(colId => {
      const cellValue = row[colId] || '';
      // 保留换行符，并设置自动换行
      const formattedValue = escapeHtml(cellValue.toString().replace(/\n/g, '<br>'));
      dataCells.push(`<td style="width: 400px;">${formattedValue}</td>`);
    });
    
    htmlContent += `<tr>${dataCells.join('')}</tr>`;
  });
  
  // 结束HTML内容
  htmlContent += `
        </tbody>
      </table>
    </body>
    </html>
  `;
  
  // 生成HTML文件并下载（Excel会自动识别并打开）
  const blob = new Blob([htmlContent], { type: 'application/vnd.ms-excel;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  
  // 创建下载链接并触发下载
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', `论文数据表_${new Date().toLocaleDateString()}.xls`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  
  ElMessage.success('表格数据导出成功（支持自动换行）');
};

// HTML特殊字符转义
const escapeHtml = (text) => {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, (char) => map[char] || char);
};

</script>

<style scoped>
.home-container {
  padding: 10px;
  height: 100%;
}
.batch-container {
    height: 100%;
    border-radius: 10px;
    border: 1px solid #ddd;
    overflow: hidden;
}

.container-head {
  height: 47px;
  line-height: 47px;
  padding: 0 20px;
  border-radius: 10px 10px 0 0;
  background: oklch(98.5% 0 0);
  border-bottom: 1px solid #ddd;
  position: relative;
  font-size: 14px;
  color: var(--primary);
}
.breadcrumb-icon{
  width: 28px;
  height: 28px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  cursor: pointer;
  float: right;
  margin-top: 9px;
}
.breadcrumb-icon:hover {
  background: var(--sidebar-hover);
}
.breadcrumb-icon .el-icon {
  color: rgba(9, 9, 11, 0.8);
  font-size: 20px;
}

.container-body {
  height: calc(100% - 48px);
  overflow: hidden;
  background: #fff;
}
.table-content {
  float: left;
  width: calc(100% - 245px);
  overflow-x: auto;
  height: 100%;
  position: relative;
}
.table-content-full {
  float: left;
  width: 100%;
  overflow-x: auto;
  height: 100%;
  position: relative;
}
.test {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow-x: auto;
}
.column-content {
  float: right;
  width: 245px;
  height: 100%;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  position: relative;
  border-left: 1px solid var(--table-border);
}
.column-head {
  padding: 0 24px;
  border-bottom: 1px solid var(--table-border);
  background: oklch(98.5% 0 0);
  height: 40px;
  line-height: 40px;
  font-weight: 400;
  color: oklch(.141 .005 285.823);
}
.column-body {
  padding: 12px;
  height: calc(100% - 40px);
  overflow-y: auto;
}
.current-column, .order-column {
  margin-bottom: 16px;
}
.order-column {
  max-height: 390px;
  overflow: hidden;
}
.column-auto {
  max-height: 100000px;
}
.column-title {
  color: oklch(70.5% .015 286.067);
  margin-bottom: 8px;
}
.column-list {
  
}
.column-list-item {
  margin-bottom: 4px;
  display: flex;
  flex-direction: row;
  color: oklch(44.2% .017 285.786);
  cursor: pointer;
  height: 32px;
  align-items: center;
  border-radius: 10px;
  padding: 0 12px;
}
.column-list-item .el-icon {
  margin-right: 18px;
  margin-top: 5px;
}
.column-list-item:hover, .column-list-more:hover{
  color: oklch(.21 .006 285.885);
  background: oklch(.967 .001 286.375);
}
.column-list-item.disabled {
  opacity: 0.5;
  cursor: default;
}
.column-list-item.disabled:hover {
  color: oklch(44.2% .017 285.786);
  background: transparent;
}
.column-list-more {
  color: oklch(55.2% .016 285.938);
  cursor: pointer;
  height: 32px;
  line-height: 32px;
  font-size: 12px;
  margin-top: 25px;
  text-align: center;
  border-radius: 10px;
}
.name-btn {
  font-size: 12px;
  padding: 4px;
  height: 24px;
  margin-top: 16px;
}
.blue-btn {
  background: var(--primary);
  color: var(--txt-color);
}
::v-deep .el-table {
  max-width: none;
  min-width: 100%;
}
::v-deep .el-table td.el-table__cell, ::v-deep .el-table th.el-table__cell.is-leaf {
  border-bottom: 1px solid var(--table-border);
}
::v-deep .el-table:not(.el-table--border) .el-table__cell {
  border-right: 1px solid var(--table-border);
}
::v-deep .el-table:not(.el-table--border) .el-table__cell:last-child {
  border-right: none;
}
::v-deep .el-table th.el-table__cell {
  background: oklch(98.5% 0 0);
  color: oklch(.141 .005 285.823);
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner, ::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: var(--primary);
  border-color: var(--primary);
}
::v-deep .el-checkbox__inner:hover {
  border-color: var(--primary);
}
::v-deep .el-scrollbar__bar.is-horizontal {
  height: 8px;
}
::v-deep .el-scrollbar__thumb {
  background-color: #000;
  opacity: 0.5;
}
</style>